package net.goutalk.glcs.module.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.temp.SaTempUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.enums.EnabledMark;
import net.goutalk.glcs.common.exception.MyException;
import net.goutalk.glcs.common.utils.RedisUtil;
import net.goutalk.glcs.config.LicenseConfig;
import net.goutalk.glcs.module.organization.entity.*;
import net.goutalk.glcs.module.organization.service.*;
import net.goutalk.glcs.module.organization.entity.*;
import net.goutalk.glcs.module.system.dto.CreateTokenDto;
import net.goutalk.glcs.module.system.dto.LoginDto;
import net.goutalk.glcs.module.system.service.ILoginService;
import net.goutalk.glcs.module.system.vo.CreateTokenVo;
import net.goutalk.glcs.module.system.vo.LoginVo;
import lombok.AllArgsConstructor;
import net.goutalk.glcs.module.organization.service.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: tanyujie
 * @Date: 2023/4/21 14:22
 */
@Service
@AllArgsConstructor
public class LoginServiceImpl implements ILoginService {

    private final IUserService userService;

    private final IUserDeptRelationService userDeptRelationService;

    private final IUserPostRelationService userPostRelationService;

    private final IPostService postService;

    private final IDepartmentService departmentService;

    private final RedisUtil redisUtil;


    private final LicenseConfig licenseConfig;

    @Override
    public LoginVo login(LoginDto dto) {
        LoginVo result = new LoginVo();

        if (licenseConfig.getEnabled()) {
            //查出所有在线用户
            List<String> onlineUser = StpUtil.searchSessionId("", 0, Integer.MAX_VALUE);

            //如果已经登录人数超过授权人数  不允许登录
            if (onlineUser.size() >= licenseConfig.getLoginMax()) {
                throw new MyException("登录人数超过授权人数，无法登录，请联系管理员！");
            }
        }


        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, dto.getUserName());
        User loginUser = userService.getOne(queryWrapper);
        if (loginUser == null || !StrUtil.equals(loginUser.getPassword(), SaSecureUtil.md5BySalt(dto.getPassword(), GlobalConstant.SECRET_KEY))) {
            throw new MyException("账号或密码不正确");
        }

        if (loginUser.getEnabledMark() == EnabledMark.DISABLED.getCode()) {
            throw new MyException("账户未启用");
        }

        //此登录接口登录web端
        StpUtil.login(loginUser.getId(), "PC");

        SaSession tokenSession = StpUtil.getTokenSession();

        List<UserDeptRelation> userDeptRelations = userDeptRelationService.list(Wrappers.lambdaQuery(UserDeptRelation.class)
                .eq(UserDeptRelation::getUserId, StpUtil.getLoginIdAsLong()));

        List<UserPostRelation> userPostRelations = userPostRelationService.list(Wrappers.lambdaQuery(UserPostRelation.class)
                .eq(UserPostRelation::getUserId, StpUtil.getLoginIdAsLong()));

        //获取登陆人所选择的身份缓存
        String postId = redisUtil.get(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId());

        Post post = new Post();
        if (StrUtil.isNotBlank(postId)) {
            post = postService.getById(postId);
        }

        if (userPostRelations.size() > 0) {
            List<Long> postIds = userPostRelations.stream().map(UserPostRelation::getPostId).collect(Collectors.toList());

            List<Post> postList = postService.listByIds(postIds);
            if (StrUtil.isBlank(postId) && CollectionUtils.isNotEmpty(postList)) {
                post = postList.get(0);
            }
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_INFO_KEY, post);
            tokenSession.set(GlobalConstant.LOGIN_USER_POST_LIST_KEY, postList);
            loginUser.setPostId(post.getId());

            //将登陆人所选择的身份缓存起来
            //切换身份的时候 会一起修改
            redisUtil.set(GlobalConstant.LOGIN_IDENTITY_CACHE_PREFIX + loginUser.getId(), post.getId());
        }

        if (userDeptRelations.size() > 0) {
            // 存当前用户所有部门到缓存
            List<Long> departmentIds = userDeptRelations.stream().map(UserDeptRelation::getDeptId).collect(Collectors.toList());
            List<Department> departmentList = departmentService.listByIds(departmentIds);
            tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_LIST_KEY, departmentList);
            //如果此人有岗位  使用岗位的deptId  找到当前组织机构
            if (ObjectUtil.isNotNull(post.getId())) {
                Department department = departmentService.getById(post.getDeptId());
                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);
                loginUser.setDepartmentId(department.getId());
            } else {

                Department department = departmentList.get(0);

                tokenSession.set(GlobalConstant.LOGIN_USER_DEPT_INFO_KEY, department);

                loginUser.setDepartmentId(department.getId());
            }

        }

        //根据登录信息  将post  和 department 信息存入用户信息中
        tokenSession.set(GlobalConstant.LOGIN_USER_INFO_KEY, loginUser);

        result.setToken(StpUtil.getTokenValue());
        return result;
    }

    @Override
    public CreateTokenVo createToken(CreateTokenDto dto) {
        CreateTokenVo vo = new CreateTokenVo();

        if(dto.getExpire() == -1){
            String token = SaTempUtil.createToken(IdUtil.fastSimpleUUID() + StringPool.UNDERSCORE + GlobalConstant.SECRET_KEY, Integer.MAX_VALUE);
            vo.setToken(token);
            return vo;
        }
        else {
            String token = SaTempUtil.createToken(IdUtil.fastSimpleUUID() + StringPool.UNDERSCORE + GlobalConstant.SECRET_KEY, dto.getExpire());
            vo.setToken(token);
            return vo;
        }

    }

}
